import {
  RequestConfig,
  useModel,
  type AxiosError,
  type AxiosResponse,
} from '@umijs/max';
import { message } from 'antd';
import { getToken, removeToken } from './utils/auth';

interface ResponseStructure {
  success: boolean;
  data?: any;
  code: number;
  msg: string;
}
export function patchRoutes({ routes, routeComponents }) {
  console.log('patchRoutes', routes, routeComponents);
}
export function patchClientRoutes({ routes }) {
//   const { setRoutes } = useModel('global', (model) => {
//     return {
//       setRoutes: model.setRoutes,
//     };
//   });
//   console.log(routes);
//   setRoutes(routes)
  // const menus = routes.filter(item => {
  //     return (item.layout ?? true)
  // }).map(item=>)
}
// export function render(oldRender) {
//     if (getToken()) {

//     }
//     oldRender()
// }
const authHeaderInterceptor = (url: string, options: RequestConfig) => {
  const { needToken = true } = options;
  const authHeader = { Authorization: getToken() };
  return {
    url: `${url}`,
    options: {
      ...options,
      interceptors: true,
      headers: needToken ? authHeader : null,
    },
  };
};
export const request: RequestConfig = {
  // errorHandler,
  // 新增自动添加AccessToken的请求前拦截器
  requestInterceptors: [authHeaderInterceptor],
  timeout: 10000,
  responseInterceptors: [
    // 一个二元组，第一个元素是 request 拦截器，第二个元素是错误处理
    [
      (response) => {
        const {
          data: { code, success, msg },
        } = response as unknown as AxiosResponse<ResponseStructure>;

        if (!success) {
          message.error(msg);
          if (code === 401) {
            removeToken();
            location.reload();
          }
          Promise.reject(new Error(msg));
        } else {
          return response.data as any;
        }
      },
      (error: AxiosError<any> | Error) => {
        return Promise.reject(
          message.error(
            'message' in error
              ? error.message
              : (error as AxiosError<any>).response?.data.msg,
          ),
        );
      },
    ],
  ],
  baseURL: '/xfj',
};
